package com.jsbj.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsbj.base.ResultBean;
import com.jsbj.tools.RequestHeaderUtils;
import com.jsbj.tools.StringUtils;
import com.jsbj.user.entities.SysRolePermission;
import com.jsbj.user.entities.SysRoleTenant;
import com.jsbj.user.entities.SysTenant;
import com.jsbj.user.entities.SysTenantPermission;
import com.jsbj.user.mapper.SysRoleTenantMapper;
import com.jsbj.user.service.ISysRolePermissionService;
import com.jsbj.user.service.ISysRoleTenantService;
import com.jsbj.user.service.ISysTenantPermissionService;
import com.jsbj.user.service.ISysTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 角色-租户信息表 服务实现类
 * </p>
 *
 * @author jsbj
 * @since 2022-03-07
 */
@Service
public class SysRoleTenantServiceImpl extends ServiceImpl<SysRoleTenantMapper, SysRoleTenant> implements ISysRoleTenantService {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ISysTenantService sysTenantService;

    @Autowired
    private ISysTenantPermissionService sysTenantPermissionService;

    @Autowired
    private ISysRolePermissionService sysRolePermissionService;

    @Override
    public Integer add(String inParam) {
        String userId = RequestHeaderUtils.getUserId(request);
        JSONObject object = JSONObject.parseObject(inParam);
        String tenants = object.getString("tenants");
        String roleId = object.getString("roleId");
        if (StringUtils.isNotEmpty(tenants)) {
            List<String> tenantList = Arrays.asList(tenants.split(","));
            for (String tenant : tenantList) {
                SysRoleTenant sysRoleTenant = new SysRoleTenant();
                sysRoleTenant.setTenantCode(tenant);
                sysRoleTenant.setRoleId(roleId);
                sysRoleTenant.setCreaterId(userId);
                sysRoleTenant.setCreateTime(new Date());
                sysRoleTenant.setUpdateId(userId);
                sysRoleTenant.setUpdateTime(new Date());
                baseMapper.insert(sysRoleTenant);
            }
        }
        String ids = object.getString("ids");
        if (StringUtils.isNotEmpty(ids)) {
            List<String> notChooseIds = Arrays.asList(ids.split(","));
            for (String id : notChooseIds) {
                SysRoleTenant sysRoleTenant = baseMapper.selectById(id);
                sysRoleTenant.setDisabled(1);
                sysRoleTenant.setUpdateId(userId);
                sysRoleTenant.setUpdateTime(new Date());
                baseMapper.updateById(sysRoleTenant);
            }
        }
        return 1;
    }

    @Override
    public void inSertData(String tenantCode, String roleId, String userId) {
        LambdaQueryWrapper<SysRoleTenant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleTenant::getDisabled, 0);
        queryWrapper.eq(SysRoleTenant::getRoleId, roleId);
        queryWrapper.eq(SysRoleTenant::getTenantCode, tenantCode);
        queryWrapper.last(" limit 1");

        if (null == baseMapper.selectOne(queryWrapper)) {
            SysRoleTenant sysRoleTenant = new SysRoleTenant();
            sysRoleTenant.setTenantCode(tenantCode);
            sysRoleTenant.setRoleId(roleId);
            sysRoleTenant.setCreaterId(userId);
            sysRoleTenant.setCreateTime(new Date());
            sysRoleTenant.setUpdateId(userId);
            sysRoleTenant.setUpdateTime(new Date());
            baseMapper.insert(sysRoleTenant);

            // 如果该项目有父级，需将父级也插入
            SysTenant sysTenant = sysTenantService.getByTenantCode(tenantCode);
            saveChild(sysTenant, roleId, userId);
        }
    }

    private void saveChild(SysTenant sysTenant, String roleId, String userId) {
        if (StringUtils.isNotEmpty(sysTenant.getParentTenantCode())) {
            SysTenant parent = sysTenantService.getByTenantCode(sysTenant.getParentTenantCode());

            SysRoleTenant sysRoleTenant = new SysRoleTenant();
            sysRoleTenant.setTenantCode(parent.getTenantCode());
            sysRoleTenant.setRoleId(roleId);
            sysRoleTenant.setCreaterId(userId);
            sysRoleTenant.setCreateTime(new Date());
            sysRoleTenant.setUpdateId(userId);
            sysRoleTenant.setUpdateTime(new Date());
            baseMapper.insert(sysRoleTenant);
        }
    }

    @Override
    public List<Map<String, Object>> getTenantAndMenuByRoleId(String roleId) {
        String userId = RequestHeaderUtils.getUserId(request);
        List<Map<String, Object>> retList = new ArrayList<>();
        // 查询已配置的租户
        List<SysTenant> sysTenants = sysTenantService.getAllTenantQx(userId, roleId);
        // 查询租户下已配置的权限菜单
        for (SysTenant sysTenant : sysTenants) {
            List<SysTenantPermission> sysTenantPermissions = sysTenantPermissionService.getTenantPermissionsByRoleId(roleId, sysTenant.getTenantCode());
            if (!CollectionUtils.isEmpty(sysTenantPermissions)) {
                Map<String, Object> ret = new HashMap<>();
                ret.put("tenantId", sysTenant.getId());
                ret.put("tenantCode", sysTenant.getTenantCode());
                ret.put("tenantName", sysTenant.getTenantName());
                ret.put("menuList", sysTenantPermissions);
                retList.add(ret);
            }
        }
        return retList;
    }

    @Override
    public ResultBean<JSONObject> saveOrUpdateData(String inParam) {
        String userId = RequestHeaderUtils.getUserId(request);

        JSONObject object = JSONObject.parseObject(inParam);
        String roleId = object.getString("roleId");
        String tenantCode = object.getString("tenantCode");
        String permissionsIds = object.getString("permissionsIds");
        if (StringUtils.isEmpty(roleId) || StringUtils.isEmpty(tenantCode) || StringUtils.isEmpty(permissionsIds)) {
            return new ResultBean<>().build("必填项不能为空！");
        }
        // 保存租户权限关系
        LambdaQueryWrapper<SysRoleTenant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleTenant::getDisabled, 0);
        queryWrapper.eq(SysRoleTenant::getRoleId, roleId);
        queryWrapper.eq(SysRoleTenant::getTenantCode, tenantCode);
        queryWrapper.last(" limit 1");
        if (null == baseMapper.selectOne(queryWrapper)) {
            this.inSertData(tenantCode, roleId, userId);
        }
        // 保存权限角色关系
        sysRolePermissionService.batchInsertData(permissionsIds, roleId, userId, tenantCode);
        return new ResultBean<>().success("处理成功！");
    }

    @Override
    public ResultBean<JSONObject> deleteData(String inParam) {
        String userId = RequestHeaderUtils.getUserId(request);

        JSONObject object = JSONObject.parseObject(inParam);
        String roleId = object.getString("roleId");
        String tenantCode = object.getString("tenantCode");
        if (StringUtils.isEmpty(roleId) || StringUtils.isEmpty(tenantCode)) {
            return new ResultBean<>().build("必填项不能为空！");
        }
        LambdaUpdateWrapper<SysRoleTenant> updateWrapper1 = new LambdaUpdateWrapper<>();
        updateWrapper1.eq(SysRoleTenant::getDisabled, 0);
        updateWrapper1.eq(SysRoleTenant::getRoleId, roleId);
        updateWrapper1.eq(SysRoleTenant::getTenantCode, tenantCode);
        SysRoleTenant sysRoleTenant = new SysRoleTenant();
        sysRoleTenant.setDisabled(1);
        sysRoleTenant.setUpdateId(userId);
        sysRoleTenant.setUpdateTime(new Date());
        baseMapper.update(sysRoleTenant, updateWrapper1);

        LambdaUpdateWrapper<SysRolePermission> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysRolePermission::getDisabled, 0);
        updateWrapper.inSql(SysRolePermission::getSysTenantPermissionId, "select id from sys_tenant_permission where disabled = 0 and tenant_code='"+tenantCode+"'");

        SysRolePermission sysRolePermissionU = new SysRolePermission();
        sysRolePermissionU.setDisabled(1);
        sysRolePermissionU.setUpdateId(userId);
        sysRolePermissionU.setUpdateTime(new Date());

        sysRolePermissionService.update(sysRolePermissionU, updateWrapper);
        return new ResultBean<>().success("处理成功！");
    }

    @Override
    public List<String> getDetail(String inParam) {
        JSONObject object = JSONObject.parseObject(inParam);
        String roleId = object.getString("roleId");
        String tenantCode = object.getString("tenantCode");
        List<String> retList = new ArrayList<>();
        // 查询租户下已配置的权限菜单
        LambdaQueryWrapper<SysRolePermission> updateWrapper = new LambdaQueryWrapper<>();
        updateWrapper.eq(SysRolePermission::getDisabled, 0);
        updateWrapper.inSql(SysRolePermission::getSysTenantPermissionId, "select id from sys_tenant_permission where disabled = 0 and tenant_code='"+tenantCode+"' and menu_type_value != '1'");
        updateWrapper.eq(SysRolePermission::getRoleId, roleId);
        List<SysRolePermission> sysRolePermissions = sysRolePermissionService.list(updateWrapper);
        for (SysRolePermission sysRolePermission : sysRolePermissions) {
            retList.add(sysRolePermission.getSysTenantPermissionId());
        }
        return retList;
    }
}
